#include "stdafx.h"
#include "LogEvent.h"

//Data structure:
//EventType	data[0]		-> type of event (for all events)
//(u_char)	data[1]		-> size of the rest of the data structure
//(byte)	data[2]		-> type
//(char*)	data[2+]	-> value
int serializeLogEvent(LogEvent event, char* buffer){
	u_int text_size = strlen(event.text.c_str()); // the size of the rest of the buffer

	u_char buffer_size = (u_char)getLogBufferSize(event);
	ZeroMemory(buffer, buffer_size);

	if(buffer != NULL && buffer_size > 0){
		buffer[0] = LOG_EVENT;
		buffer[1] = text_size;

		char* dst = (buffer + sizeof(LOG_EVENT) + sizeof(text_size)); // gives an index to start writing the log message string
		const char* str = event.text.c_str();

		for (u_int i = 0; i < text_size; i++) {
			buffer[i+2] = str[i];
		}

		return 0;
	}else{ 
		fprintf(stdout, "Meh. The buffer is NULL or the buffer_size is too small (0 or less)");
		return -1;
	}
}

//Data structure:
//EventType	data[0]		-> type of event (for all events)
//(u_char)	data[1]		-> size of the rest of the data structure
//(byte)	data[2]		-> type
//(char*)	data[2+]	-> value

int deserializeLogEvent(char* buffer, LogEvent *event){
	if(buffer != NULL){
		// event type is in the 0th spot
		EventType eventType = (EventType)buffer[0];
		if(eventType != LOG_EVENT){
			fprintf(stdout, "Deserialization failed: The type of event is not LogEvent. EventType = %d\n", buffer[0]);
			return -1;
		}

		//read data after EventType and text size
		char* textPtr = (buffer + 2); 

		std::string eventText(textPtr);
		event->text = eventText;

		return 0;
	}else{
		fprintf(stdout, "Deserialization failed: Buffer not allocated or too small");
		return -1;
	}
}

int getLogBufferSize(LogEvent event) {
	u_int bytesWritten = strlen(event.text.c_str()); // the size of the rest of the buffer
	
	//WARNING: sizeof(LOG_EVENT) might differ in different compilers
	//See current C99 Standard Draft : http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf
	//Section : 6.7.2.2 Enumeration specifiers

	return sizeof(LOG_EVENT) + sizeof(bytesWritten) + strlen(event.text.c_str());
}
